<?php
require_once 'ini.php';

if (isset($_POST['act']) && $_POST['act'] == 'update') {
    $uri = 'http://ddnerp.stosz.com/Domain/Api/get_all?name=www.lysxo.com';
    $info = file_get_contents($uri);
    $info = json_decode($info, true);
    if (!$info['status']) {
        echo json_encode(['ret' => 0, 'msg' => '更新失败']);exit;
    }
    //获取已有的数据
    $currency = new \admin\helper\currency($register);
    $list =  $register->get("db")->select('currency', '*');
    $currCurrencyIDLists = array_column($list, 'currency_id');
    //erp货币数组
    $erpCurrency = $info['data']['currency'];

    //遍历判断数据库中是否存在
    foreach ($erpCurrency as $key => $val) {
        $data = [];
        $erpCurrencyID = $val['id_currency'];
        //判断是否是新的货币
        if (in_array($erpCurrencyID, $currCurrencyIDLists)) {
            //更新
            $data['currency_title'] = $val['title'];
            $data['currency_code'] = $val['code'];
            $data['symbol_left'] = $val['symbol_left'];
            $data['symbol_right'] = $val['symbol_right'];
            $data['update_time'] = $val['updated_at'];
            $map = ['currency_id' => $val['id_currency']];
            $currency->updateCurrency($data, $map);
        } else {
            //添加
            $data['currency_id'] = $val['id_currency'];
            $data['currency_title'] = $val['title'];
            $data['currency_code'] = $val['code'];
            $data['symbol_left'] = $val['symbol_left'];
            $data['symbol_right'] = $val['symbol_right'];
            $data['update_time'] = $val['updated_at'];
            $ret = $currency->addCurrency($data);
            if (!$ret) {
                echo json_encode(['ret' => 0, 'msg' => '同步失败']);exit;
            }
        }
    }
    echo json_encode(['ret' => 1, 'msg' => '更新成功']);
} else {
    $currency = new \admin\helper\currency($register);
    $data = $currency->lists();
    $data['admin'] = $_SESSION['admin'];
    // $register->get('view')->display('currency/edit.twig', $data);
    echo json_encode($data);
}
